package com.quanshu.exchange.ui.gui.message.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.entity.tmp.TmpLabelBean;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/21.
 */

public class AddLabelActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.commit_btn)
    LinearLayout commitBtn;
    @BindView(R.id.label_name_edit)
    EditText labelNameEdit;
    @BindView(R.id.label_member_num)
    TextView labelMemberNum;
    @BindView(R.id.lable_image)
    ImageView lableImage;
    @BindView(R.id.add_member_lable_rel)
    RelativeLayout addMemberLableRel;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private SingleAdapter<UserEntity> adapter;
    private String labelName;
    private List<UserEntity> labelMember = new ArrayList<>();
    private List<String> beSelectedMember;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_label_layout);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initView() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<UserEntity>(this, R.layout.item_simple_friend_layout) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper<UserEntity> wrapper, UserEntity item, int position) {
                holder.setRoundImageUrl(R.id.friend_avatar, item.getAvatar(), R.drawable.default_avatar);
                holder.setText(R.id.friend_name, AppUtils.getUserName(item));
                String letter = AppUtils.getUserInitialLetter(item);
                // 处理分割线
                int nextPosition = position + 1;
                if (nextPosition < labelMember.size()) {
                    UserEntity nextUser = labelMember.get(position + 1);
                    String nextHead = AppUtils.getInitialLetter(AppUtils.getUserName(nextUser));
                    if (letter.equals(nextHead)) {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.VISIBLE);
                    } else {
                        holder.setVisibility(R.id.item_contacts_bottom_divider, View.GONE);
                    }
                }
                if (position == labelMember.size() - 1) {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.VISIBLE);
                } else {
                    holder.setVisibility(R.id.item_contacts_last_bottom_divider, View.GONE);
                }
                // 处理head字母
                if (position == 0) {
                    holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                    holder.setText(R.id.friend_sort_letter, letter);
                } else {
                    int lastPosition = position - 1;
                    if (lastPosition < 0) {
                        lastPosition = 0;
                    }
                    UserEntity lastUser = labelMember.get(lastPosition);
                    if (letter.equals(AppUtils.getUserInitialLetter(lastUser))) {
                        holder.setVisibility(R.id.friend_sort_letter, View.GONE);
                    } else {
                        holder.setVisibility(R.id.friend_sort_letter, View.VISIBLE);
                        holder.setText(R.id.friend_sort_letter, letter);
                    }
                }
                holder.setOnClickListener(R.id.label_delete, view -> {
                    labelMember.remove(item);
                    beSelectedMember.remove(item.getMemberid());
                    adapter.notifyDataSetChanged();
                });
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initData() {
        List<UserEntity> userEntityList = UserDao.getInstance().queryForAll();
        if (userEntityList != null && beSelectedMember != null) {
            for (UserEntity userEntity : userEntityList) {
                if (beSelectedMember.contains(userEntity.getMemberid())) {
                    labelMember.add(userEntity);
                }
            }
        }
        if (labelMember != null && labelMember.size() > 0) {
            AppUtils.sortDataByPinYin(labelMember);
            adapter.setData(labelMember);
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(commitBtn, aVoid -> doCommit());
        RxViewHelper.getInstance().afterTextChangeEvents(labelNameEdit, afterText -> labelName = afterText.editable().toString());
        RxViewHelper.getInstance().clicks(addMemberLableRel, aVoid -> goSelectFriendActivity());

    }

    private void goSelectFriendActivity() {
        if (labelName == null || labelName.trim().length() < 1) {
            ToastHelper.toast("请输入标签名称");
            return;
        }
        Intent intent = new Intent(this, SelectFriendActivity.class);
        if (beSelectedMember != null && beSelectedMember.size() > 0) {
            intent.putExtra("List<String>", (Serializable) beSelectedMember);
        }
        startActivityForResult(intent, 0x01);
    }

    private void doCommit() {

        if (labelName == null || labelName.trim().length() < 0) {
            ToastHelper.toast("请输入标签名称");
            return;
        }
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .addFriendLabel(AppUtils.getSignParams(currentUser.getMemberid(), labelName), currentUser.getMemberid(), labelName)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<TmpLabelBean>>() {
                    @Override
                    public void onSuccess(BaseResponse<TmpLabelBean> response) {
                        ToastHelper.toast("创建成功");
                        labelNameEdit.setKeyListener(null);
                        TmpLabelBean tmpLabelBean = response.getInfo();
                        doCommitLabelMember(tmpLabelBean.getLabel_id());
                    }
                });
    }

    private void doCommitLabelMember(String labelId) {
        if (labelMember != null && labelMember.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < labelMember.size(); i++) {
                stringBuffer.append(labelMember.get(i).getMemberid());
                if (i != labelMember.size() - 1) {
                    stringBuffer.append(" ,");
                }
            }
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .addMember2FriendLabel(AppUtils.getSignParams(currentUser.getMemberid(), labelId, stringBuffer.toString()), currentUser.getMemberid(), labelId, stringBuffer.toString())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse>() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            UserDao.getInstance().save(labelMember);
                            finish();
                        }
                    });
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {
                beSelectedMember = (List<String>) data.getSerializableExtra("List<String>");
                initData();
            }
        }
    }
}
